package com.dongdongshop.mq;

import com.dongdongshop.mapper.TbSeckillOrderMapper;
import com.dongdongshop.pojo.TbSeckillGoods;
import com.dongdongshop.pojo.TbSeckillOrder;
import com.dongdongshop.vo.QueueSeckill;
import com.dongdongsop.constant.CatchConstant;
import com.dongdongsop.util.IdWorker;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

@Component
@RocketMQMessageListener(consumerGroup = "seckill-goods-consumer", topic = "seckill-goods-topic")
public class SeckillGoodsConsumer implements RocketMQListener<QueueSeckill> {

    @Autowired
    private IdWorker idWorker;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private TbSeckillOrderMapper seckillOrderMapper;

    @Override
    public void onMessage(QueueSeckill queueSeckill) {
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        Long seckillId = queueSeckill.getSeckillId();
        String userName = queueSeckill.getUserName();
        TbSeckillGoods goods = (TbSeckillGoods) redisTemplate.boundHashOps(CatchConstant.SECKILL_GOODS).get(seckillId);
        //创建订单
        Long orderId = idWorker.nextId();
        TbSeckillOrder order = new TbSeckillOrder();
        order.setId(orderId);
        order.setUserId(userName);
        order.setSellerId(goods.getSellerId());
        order.setStatus("0");
        order.setSeckillId(goods.getId());
        order.setCreateTime(new Date());
        order.setMoney(goods.getCostPrice());
        seckillOrderMapper.insertSelective(order);
        //当订单创建成功之后，我们将ID放入redis中
        redisTemplate.boundHashOps(CatchConstant.SECKILL_ORDER_ID).put(userName,orderId);
    }
}
